package demo03_pub_sub;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @Description 发布订阅模式的消息生产者：需要先启动消费者，因为没有消费者就没有绑定的队列，发过去的消息就会丢失！
 * @Author shihan
 * @Date 2020/12/20 14:48
 * @Version 1.0
 */
public class PSProducer {

    // fanout 类型的交换器名称
    public static final String EXCHANGE_NAME_FANOUT = "exc.fan.name";

    public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri("amqp://root:123456@192.168.66.129:5672/%2f");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        // 声明一个 fanout 类型的 Exchange
        channel.exchangeDeclare(EXCHANGE_NAME_FANOUT, BuiltinExchangeType.FANOUT);

        // 发送消息：指明 Exchange 名称、Routing key 置为 空串
        for (int i = 1; i <= 10; i++) {
            try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
            channel.basicPublish(EXCHANGE_NAME_FANOUT,"",null,("发布订阅模式--消息：" + i).getBytes("utf-8"));
        }

        // 生产环境，使用池化技术
        channel.close();
        connection.close();

    }

}
